<template>
  <div class="title-btns block">
    <el-button type="primary" @click="addClickEvent" >
      {{$t('ship.button.plus')}}
    </el-button>
  </div>


  <el-table
      v-if="refreshTable" 
      :data="listData"
      row-key="deptId"  
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
    <el-table-column prop="deptId" label="Id" width="80"/>
      <el-table-column prop="deptName" label="Department Name" width="260"/>
      <el-table-column prop="orderNum" label="Sort" width="200"/> 
      <el-table-column prop="status" label="Status" width="100">
        <template #default="scope"> 
          <span>{{ statuss[scope.row.status] }}</span> 
        </template>
      </el-table-column>
      <el-table-column label="Time Created" align="center" prop="createTime" width="200">
        <template #default="scope">
          <span>{{ convertDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Operation" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <span  class="btn-primary" @click="editClickEvent(scope.row)">{{$t('ship.button.edit')}}</span>&nbsp;
          <span class="btn-primary" @click="removeClickEvent(scope.row.id)">{{$t('ship.button.remove')}}</span>
        </template>
      </el-table-column>
    </el-table>
 

  <el-dialog
      :width="500"
      :title="dialogTitle"
       destroy-on-close
       v-model="dialogFormVisible"
       @close="orgForm.resetFields()">
    <el-form :model="formParam" :rules="rules" ref="orgForm">

      <el-form-item label="Parent Department" prop="parentId">
        <el-tree
            ref="dialogTree" 
            :data="listData"
            node-key="deptId" 
            :default-checked-keys="formParam.parentId"
            :props="defaultProps"
        /> 
      </el-form-item>
      <el-form-item label="Department Name" label-width="80px" prop="deptName">
        <el-input v-model="formParam.deptName" autocomplete="off" clearable></el-input>
      </el-form-item>

      <el-form-item label="Sort" label-width="80px" prop="orderNum">
        <el-input v-model="formParam.orderNum" autocomplete="off" maxlength="11" clearable></el-input>
      </el-form-item>
 
      <el-form-item label="Status" label-width="80px" prop="status">
        <el-select v-model="formParam.status" placeholder="Please choose status">
          <el-option
            :key="index"
            :label="item"
            :value="index"
            v-for="(item, index) in statuss"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
      
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogFormVisible=false">取 消</el-button>
      <el-button @click="resetForm" type="warning">重 置</el-button>
      <el-button type="primary" @click="submitForm">保 存</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script lang="ts"  setup>
import { ref,  onMounted } from 'vue'
import service from '@/utils/request'
import { hasAuth } from "@/utils/auth.js";
import {  convertDate } from "@/utils/date"
import { ElNotification, ElMessageBox } from 'element-plus' 
import {useMixinAuth} from '@/components/mixin/auth.js'
const auth = useMixinAuth();
const orgForm = ref<any>(null)
const dialogTitle = ref('新增机构')
let isAdd = false
const initForm = {
  deptId: undefined,
  parentId: undefined,
  deptName: undefined,
  orderNum: undefined,
  leader: undefined,
  phone: undefined,
  email: undefined,
  departments: [],
  status: "0"
}
const formParam = ref<any>(Object.assign({}, initForm))

// let isExpandAll =true

// const phoneValid = (_: any, value: any, callback: any) => {
//   if (value === '') {
//     callback(new Error('请输入手机号码'));
//   } else if (!/^1\d{10}$/.test(value)) {
//     callback(new Error('手机格式不合法!'));
//   } else {
//     callback();
//   }
// }

const rules = ref( {
  parentId: [
    { required: true, message: "上级部门不能为空", trigger: "blur" }
  ],
  deptName: [
    { required: true, message: "部门名称不能为空", trigger: "blur" }
  ],
  // phone: [
  //   { required: false ,validator: phoneValid,  trigger: 'change' }
  // ], 
  enable: [
    { type: 'number', required: true, message: '请选择启用状态', trigger: 'change' }
  ],
  // check: [
  //   { type: 'number', required: true, message: '请选择审核状态', trigger: 'change' }
  // ],
  // img: [
  //   { required: true, message: '请上传营业执照', trigger: 'change' }
  // ],
})
const statuss: any = {
  0: '正常',
  1: '停用',
}
 
const listData = ref([])
const refreshTable = async () => {
  listData.value = (await service.get('manager/department')).data
}
const dialogFormVisible = ref(false)
 

const addClickEvent = () => {
  dialogTitle.value = 'New Department'
  dialogFormVisible.value = true
  Object.assign(formParam.value, initForm)
}

let editRowId: any
const editClickEvent = (row: any) => {
  editRowId = row.id
  dialogTitle.value = 'Update Department'
  dialogFormVisible.value = true
  Object.keys(initForm).forEach(k =>  (formParam.value[k] = row[k]))
 
}

const removeClickEvent = (id: any) => {
  ElMessageBox.confirm('Confirm to remove Department？', 'Confirmation Information', {type: 'warning'}).then(async () => {
    await service.delete(`shipping/department/${id}`)
    // @ts-ignore
    ElNotification.success({title: 'Confirm', message: 'Confirm to remove Department', position: 'bottom-right'})
    refreshTable()
  })

}

const resetForm = () => {
  // @ts-ignore
  orgForm.value.resetFields()
}

const submitForm = () => {
  // @ts-ignore
  orgForm.value.validate(async (valid) => {
    if (!valid) {
      // @ts-ignore 
      return
    }

    const formData = new FormData()
    document.querySelector('#upload-file')
    for (const [k, n] of Object.entries(formParam.value)) {
      // if (k == 'img') {
      //   // @ts-ignore
      //   uploadFile.files.length > 0 && formData.append(k, uploadFile.files[0])
      //   continue
      // }
      // @ts-ignore
      formData.append(k, n)
    }
 
    await service[isAdd? 'post': 'put']('shipping/department'  , formParam)
    // @ts-ignore
    ElNotification.success({ title: '提示信息', message: '保存成功', position: 'bottom-right' })
    dialogFormVisible.value = false
    refreshTable()
  })
}

 
const defaultProps = {
      label: 'deptName',
      key: 'deptId',
      children: 'children'
    }
    
// const normalizer = (node: any) =>{
//   if (node.children && !node.children.length) {
//     delete node.children;
//   }
//   return {
//     id: node.deptId,
//     label: node.deptName,
//     children: node.children
//   };
// }


onMounted(() => refreshTable()) 


</script>

<style scoped lang="scss" src="./index.scss"></style>
